package controller

import (
	"encoding/json"
	"gitee.com/kisgod/Lamborighi/Server/app/common"
	"gitee.com/kisgod/Lamborighi/Server/config"
	"gitee.com/kisgod/Lamborighi/Server/util"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Controller struct{}

type ResponseStatus int

const (
	ResSuccess      ResponseStatus = http.StatusOK                  // 200：请求成功
	ResSaved        ResponseStatus = http.StatusCreated             // 201：创建、修改成功
	ResDeleted      ResponseStatus = http.StatusNoContent           // 204：删除成功
	ResBadRequest   ResponseStatus = http.StatusBadRequest          // 400：参数错误
	ResUnauthorized ResponseStatus = http.StatusUnauthorized        // 401：未登录
	ResFrobidden    ResponseStatus = http.StatusForbidden           // 403：禁止访问
	ResNotFound     ResponseStatus = http.StatusNotFound            // 404：未找到
	ResServerError  ResponseStatus = http.StatusInternalServerError // 500：系统错误
)

type Response struct {
	Status    ResponseStatus
	Data      interface{}
	ErrorCode common.ErrorCode
	Error     string
}

func (*Controller) response(ctx *gin.Context, res Response) {
	if res.ErrorCode != common.StatusOk {
		if resString, err := json.Marshal(res); err == nil {
			util.Logger.Error(string(resString))
		} else {
			util.Logger.Error("Unresolved Logging Error")
		}
	} else {
		if config.GetLogRes() {
			if resString, err := json.Marshal(res); err == nil {
				util.Logger.Info(string(resString))
			} else {
				util.Logger.Error("Unresolved Logging Res")
			}
		}
	}

	ctx.JSON(int(res.Status), res)
	return
}

func (con *Controller) ParamError(c *gin.Context) {
	con.response(c, Response{
		Status:    ResBadRequest,
		ErrorCode: common.ErrorParams,
		Error:     "Param Error"})
}

func init() {

}
